/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.clientapi;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.compression.ZlibCodecFactory;
import io.netty.handler.codec.compression.ZlibWrapper;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLException;

/**
 *
 * @author ChengJili
 */
class TradeNettyClientInitializer extends ChannelInitializer<SocketChannel> {

    private final boolean isSSL;
    private final boolean isZlib;
    private SslContext sslCtx;
    private final TradeRequest tradeClient;

    public TradeNettyClientInitializer(boolean isSSL, boolean isZlib,TradeRequest tradeClient) {
        this.isSSL = isSSL;
        this.isZlib = isZlib;
        this.tradeClient=tradeClient;
    }


    @Override
    public void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();

        if (isSSL) {
            try {
                sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
                pipeline.addLast(sslCtx.newHandler(ch.alloc()));
            } catch (SSLException ex) {
                Logger.getLogger(TradeNettyClientInitializer.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }

        // Enable stream compression (you can remove these two if unnecessary)
        if (isZlib) {
            pipeline.addLast(ZlibCodecFactory.newZlibEncoder(ZlibWrapper.GZIP));
            pipeline.addLast(ZlibCodecFactory.newZlibDecoder(ZlibWrapper.GZIP));
        }
        // Add the number codec first,
        pipeline.addLast(new MsgDecoder());
        pipeline.addLast(new MsgEncoder());
        
        // and then business logic.
        pipeline.addLast(new TradeClientHanlder(tradeClient));
    }
}
